package org.autumn.review.thread;

import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;

/**
 * Exception in thread "m3" java.lang.IndexOutOfBoundsException: Index: 0, Size: 0
 * 	at java.util.ArrayList.rangeCheck(ArrayList.java:659)
 * 	at java.util.ArrayList.remove(ArrayList.java:498)
 * 	at org.autumn.review.thread.SubThreadSafe.lambda$m3$0(TestSubClass.java:44)
 * 	at java.lang.Thread.run(Thread.java:750)
 *
 * 	multi thread concurrent modify size ,the size is not atomic so will throw IndexOutOfBoundsException
 */
public class TestSubClass {
    public static void main(String[] args) {
        for (int i = 0; i < 2; i++) {
            Thread t = new Thread(() -> {
                new SubThreadSafe().m1(200);
            }, "t" + i);
            t.start();
        }
    }
}

@Slf4j
class ThreadSafe {
    public void m1(int loopNum) {
        ArrayList<Object> list = new ArrayList<>();
        for (int i = 0; i < loopNum; i++) {
            m2(list);
            m3(list);
        }
        log.info("size -> {}", list.size());
    }

    public void m2(ArrayList<Object> list) {
        list.add(1);
    }

    public void m3(ArrayList<Object> list) {
        list.remove(0);
    }
}

@Slf4j
class SubThreadSafe extends ThreadSafe {
    @Override
    public void m3(ArrayList<Object> list) {
        Thread m3 = new Thread(() -> {
            list.remove(0);
        }, "m3");
        m3.start();
    }
}